package org.csu.linkgame.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.csu.linkgame.domain.User;
import org.csu.linkgame.service.UserService;
import org.csu.linkgame.mapper.UserMapper;
import org.csu.linkgame.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

/**
* @author Pluto
* @description 针对表【user】的数据库操作Service实现
* @createDate 2022-08-31 10:51:55
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Autowired
    private UserMapper userMapper;

    // 事务管理
    @Transactional
    public int userRegister(String username, String password) {
        // 并发线程互斥锁
        synchronized (this) {
            // 1.根据用户查询，这个用户是否已经被注册
            List<User> users = userMapper.selectAllByUsername(username);
            //2.如果没有被注册则进行保存操作
            if (users.size() == 0) {
                String md5Pwd = MD5Utils.md5(password);
                User user = new User();
                user.setUsername(username);
                user.setPassword(md5Pwd);
                user.setIsAdmin(0);
                user.setUserGoal("0");
                user.setUserPort("8888");
                user.setUserRank("7");
                int i = userMapper.insertSelective(user);
                if (i > 0) {
                    return 1;// 注册成功！
                } else {
                    return -1;// 注册失败！
                }
            } else {
                return 0;// 用户名已经被注册！
            }
        }
    }

    public int checkLogin(String username, String password) {
        List<User> users = userMapper.selectAllByUsername(username);

        if(users.size() == 0){
            return 0;// 登录失败，用户名不存在！
        }else{
            String md5Pwd = MD5Utils.md5(password);
            if(md5Pwd.equals(users.get(0).getPassword())){
                return 1;// 登录验证成功
            }else{
                return -1;// 登录失败，密码错误！
            }
        }
    }

    public User getUserInfoByUsername(String username) {
        List<User> users = userMapper.selectAllByUsername(username);
        if (users.size() > 0) {
            return userMapper.selectAllByUsername(username).get(0);
        } else {
            return null;
        }
    }

    public List<User> getAllUserInfo() {
        return userMapper.selectALl();
    }

    public int deleteUserByUsernameList(Collection<String> usernameList) {
        return userMapper.deleteByUsernameIn(usernameList);
    }

    public List<User> getUsersByKeyword(String keyword) {
        return userMapper.selectByKeyword(keyword);
    }

    public int insertNewUserInfo(User user) {
        return userMapper.insertAll(user);
    }

    public int updateUserInfoCol(User user) {
        return userMapper.updateSelective(user);
    }
}




